package com.zhangmeng.online.exam.ui.admin;

import com.alibaba.fastjson2.JSONObject;
import com.zhangmeng.online.exam.ui.utils.ApiUtils;
import com.zhangmeng.online.exam.ui.utils.AlertUtils;
import com.zhangmeng.online.exam.ui.utils.HttpUtils;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zm
 * @date 2025/3/4 17:45
 * @version: 1.0
 */
public class LoginPage extends AnchorPane {


    private TextField username;
    private PasswordField password;
    private TextField verificationCode;

    private Button button1;

    public LoginPage() {

        ColumnConstraints column1 = new ColumnConstraints();
        column1.setHgrow(Priority.SOMETIMES);
        column1.setMaxWidth(229.0);
        column1.setMinWidth(10.0);
        column1.setPrefWidth(38.0);

        ColumnConstraints column2 = new ColumnConstraints();
        column2.setHgrow(Priority.SOMETIMES);
        column2.setMaxWidth(423.0);
        column2.setMinWidth(10.0);
        column2.setPrefWidth(248.0);

        RowConstraints row1 = new RowConstraints();
        row1.setMaxHeight(174.0);
        row1.setMinHeight(10.0);
        row1.setPrefHeight(60.0);
        row1.setVgrow(Priority.SOMETIMES);

        RowConstraints row2 = new RowConstraints();
        row2.setMaxHeight(206.0);
        row2.setMinHeight(10.0);
        row2.setPrefHeight(47.0);
        row2.setVgrow(Priority.SOMETIMES);

        RowConstraints row3 = new RowConstraints();
        row3.setMaxHeight(206.0);
        row3.setMinHeight(10.0);
        row3.setPrefHeight(47.0);
        row3.setVgrow(Priority.SOMETIMES);

        RowConstraints row4 = new RowConstraints();
        row4.setMaxHeight(206.0);
        row4.setMinHeight(10.0);
        row4.setPrefHeight(47.0);
        row4.setVgrow(Priority.SOMETIMES);

        //        <GridPane layoutX="485.0" layoutY="59.0" prefHeight="159.0" prefWidth="275.0" AnchorPane.bottomAnchor="97.0" AnchorPane.leftAnchor="125.0" AnchorPane.rightAnchor="127.0" AnchorPane.topAnchor="59.0">
        GridPane gridPane = new GridPane();
        gridPane.getColumnConstraints().addAll(column1, column2);
        gridPane.getRowConstraints().addAll(row1, row2, row3, row4);
        gridPane.setLayoutX(485.0);
        gridPane.setLayoutY(59.0);
        gridPane.setPrefHeight(200);
        gridPane.setPrefWidth(300);
        AnchorPane.setBottomAnchor(gridPane, 90.0);
        AnchorPane.setLeftAnchor(gridPane, 125.0);
        AnchorPane.setRightAnchor(gridPane, 127.0);
        AnchorPane.setTopAnchor(gridPane, 59.0);

        Label label1 = new Label("账号");
        Label label2 = new Label("密码");
        username = new TextField();
        password = new PasswordField();
        button1 = new Button("登录");
        button1.setMnemonicParsing(false);
        button1.setPrefHeight(23.0);
        button1.setPrefWidth(178.0);

        gridPane.add(label1, 0, 0);
        gridPane.add(label2, 0, 1);
        gridPane.add(username, 1, 0);
        gridPane.add(password, 1, 1);


        //验证码
        ImageView imageView = new ImageView(new Image(ApiUtils.API_URL + "/verificationCode/generate"));
        imageView.setFitHeight(30);
        imageView.setFitWidth(100);
        verificationCode = new TextField();
//        verificationCode.setPrefWidth(100);
//        verificationCode.setPrefHeight(23);

        Label label3 = new Label("验证码");
        gridPane.add(label3, 0, 2);
        imageView.setOnMouseClicked(event -> {
            imageView.setImage(new Image(ApiUtils.API_URL + "/verificationCode/generate"));
        });

        HBox hBox = new HBox(10);
        hBox.setAlignment(Pos.CENTER);
        hBox.getChildren().addAll(verificationCode, imageView);
        gridPane.add(hBox, 1, 2);

        gridPane.add(button1, 1, 3);
        getChildren().add(gridPane);

        username.setText("admin");
        password.setText("123456");

        button1.setOnAction(event -> {
            login();
        });

    }

    private void login() {

        //TODO 登录逻辑
        Map<String, Object> params = new HashMap<>();
        params.put("username", username.getText());
        params.put("password", password.getText());
        params.put("captcha", verificationCode.getText());
        String response = HttpUtils.POST(ApiUtils.API_URL + "/login", params);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getIntValue("code") == 2001) {
            Map<String, Object> data = (Map<String, Object>) jsonObject.get("data");
            Object token = data.get("token");
            HttpUtils.USER_INFO.put("token", token);
            new Thread(this::user_type).start();
            Alert alert = AlertUtils.alert_msg(jsonObject.getString("message"));

            MyScheduledService myService = new MyScheduledService();
            //myService.setDelay(Duration.seconds(5));//延迟
            myService.setPeriod(Duration.millis(500));//时间周期
            myService.setRestartOnFailure(true);
            myService.setMaximumFailureCount(4);//设置最大失败次数

            myService.progressProperty().addListener(new ChangeListener<Number>() {
                @Override
                public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                    System.out.println("progressProperty:" + newValue.intValue());
                }
            });

            myService.valueProperty().addListener(new ChangeListener<Number>() {
                @Override
                public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                    if (newValue != null) {
                        System.out.println("progressProperty:" + newValue.intValue());
                    }
                }
            });

            myService.lastValueProperty().addListener(new ChangeListener<Number>() {
                @Override
                public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {

                    if (newValue != null) {
                        System.out.println("lastValueProperty:" + newValue.intValue());
                        if (newValue.intValue() == 3) {
                            myService.cancel();
                            alert.close();
                            success();
                        }
                    }
                }
            });

            myService.start();


        } else {
            AlertUtils.alert_warning(jsonObject.getString("message"));
        }
    }

    private void user_type() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", HttpUtils.USER_INFO.get("token"));
        String response = HttpUtils.GET(ApiUtils.API_URL + "/user/getUserInfo", params);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getIntValue("code") == 200) {
            Map<String, Object> data = (Map<String, Object>) jsonObject.get("data");
            String type = data.get("type").toString();
            HttpUtils.USER_INFO.put("type", type);
        }
    }

    private void success() {
        String type = HttpUtils.USER_INFO.get("type").toString();

        switch (type) {
            case "STUDENT" -> user_page();
            case "ADMIN" -> admin_page();
        }
    }

    private void user_page() {
        Scene scene = button1.getScene();
        Stage window = (Stage) scene.getWindow();
        window.close();

        Stage stage = new Stage();

        //判断
        PaperPage paperPage = new PaperPage(new HashMap<>());
        scene = new Scene(paperPage, 1280, 720);
        stage.setScene(scene);
        stage.setTitle("在线考试系统");
        stage.show();
    }

    private void admin_page() {
        Scene scene = button1.getScene();
        Stage window = (Stage) scene.getWindow();
        window.close();

        Stage stage = new Stage();
        IndexPage indexPage = new IndexPage();

        scene = new Scene(indexPage, 1280, 720);
        stage.setScene(scene);
        stage.setTitle("在线考试系统");
        stage.show();
    }

    class MyScheduledService extends ScheduledService<Number> {

        int sum = 0;

        @Override
        protected Task<Number> createTask() {

            return new Task<Number>() {
                @Override
                protected Number call() throws Exception {
                    sum = sum + 1;

                    return sum;
                }

                @Override
                protected void updateValue(Number value) {

                    super.updateValue(value);
//                    System.out.println("updateValue");
                    if (value.intValue() == 10) {
                        MyScheduledService.this.cancel();
                    }

                }
            };
        }
    }
}